package com.svmc.app.task.alarm;

import java.util.ArrayList;
import java.util.Calendar;

import com.svmc.app.task.adapter.DbAdapter;
import com.svmc.app.task.utils.CommonDefine;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class MyAlarmManager implements CommonDefine {
	Context mcontext;
	PendingIntent myPendingIntent;
	AlarmManager myalarm;
	public MyAlarmManager(Context mcontext) {
		super();
		this.mcontext = mcontext;
		myalarm = (AlarmManager) mcontext
				.getSystemService(mcontext.ALARM_SERVICE);

	}

	/**
	 * Single alarm not data
	 * 
	 * @param timeReminder
	 * @param unique_requestcode
	 */
	public void SingleAlarm(Calendar timeReminder, int unique_requestcode) {
		Intent alarmIntent = new Intent(mcontext, AlarmService.class);
		PendingIntent myPendingIntent = PendingIntent.getBroadcast(mcontext,
				unique_requestcode, alarmIntent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
		
		myalarm.set(AlarmManager.RTC_WAKEUP, timeReminder.getTimeInMillis(),
				myPendingIntent);
	}

	/**
	 * Single alarm with data
	 * 
	 * @param timeReminder
	 * @param uique_requescode
	 * @param pathRing
	 */
	public void SingleAlarmWithData(Calendar timeReminder,
			int uique_requescode, long id) {
		Intent alarmIntent = new Intent(mcontext, AlarmService.class);
		alarmIntent.putExtra(ALARM_SERVICE_ID_TASK, id);
		myPendingIntent = PendingIntent.getBroadcast(mcontext,
				uique_requescode, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);

		
		myalarm.set(AlarmManager.RTC_WAKEUP, timeReminder.getTimeInMillis(),
				myPendingIntent);

	}
/**
 *  Cancel alarm when alarm sended to system.
 * @param requestcode
 */
	public void cancelAlarm(int requestcode) {
		Intent cancelIntent = new Intent(mcontext, AlarmService.class);
		myPendingIntent = PendingIntent.getBroadcast(mcontext,
				requestcode, cancelIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//		AlarmManager myCancelAlram = (AlarmManager) mcontext
//				.getSystemService(mcontext.ALARM_SERVICE);
		myalarm.cancel(myPendingIntent);
	}
/**
 * Cancel all alarm is registed to system.
 */
	public void deleteAllAlarm() {
		DbAdapter db = new DbAdapter(mcontext);
		ArrayList<Integer> listID = db.getAllIdAlarm();
		Intent cancelAllAlarm = new Intent(mcontext, AlarmService.class);
		for(Integer idAlarm : listID){
			System.out.println(idAlarm.intValue());
			myPendingIntent = PendingIntent.getBroadcast(mcontext, idAlarm.intValue(), cancelAllAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
			myalarm.cancel(myPendingIntent);
		}
		
	}

}
